package com.jair.crawler.opm;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.StandardSocketOptions;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;

import net.sf.json.JSONObject;

public class main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		WebClient webClient =  new WebClient(BrowserVersion.CHROME,"127.0.0.1",8888);//创建WebClient
		webClient.getOptions().setUseInsecureSSL(true);
		webClient.getOptions().setThrowExceptionOnScriptError(false);
		//webClient.setJavaScriptTimeout(10041);
		webClient.getOptions().setJavaScriptEnabled(false);
		webClient.getOptions().setCssEnabled(false);
		//webClient.getCookieManager().setCookiesEnabled(true);
		//webClient.setAjaxController(new NicelyResynchronizingAjaxController());
		//webClient.getOptions().setTimeout(20000);
		boolean cookie_enable = false;
		boolean success_flag = false;
		try {
			FileReader cookieFr = null;
			try {
				cookieFr = new FileReader("cookie");
				BufferedReader br = new BufferedReader(cookieFr);
				String line = "";
				while ( (line=br.readLine()) != null ) {
					 JSONObject jo = JSONObject.fromObject(line);
					 Cookie co = new Cookie(jo.getString("domain"), jo.getString("name"), jo.getString("value"), jo.getString("path"),null, (Boolean)jo.get("secure"), (Boolean)jo.get("httpOnly"));
					 webClient.getCookieManager().addCookie(co);
				}
				cookie_enable = true;
				cookieFr.close();
			}catch(FileNotFoundException e){
				System.out.println("没有cookie文件");
			}finally{
				if(cookieFr != null){
					cookieFr.close();
				}
			}
			HtmlPage page2 = null;
			if(cookie_enable){
				//把cookie放到header
				
				String url2 = "https://opm.be.mi.com/sqlquery/index";
				WebRequest request = new WebRequest(new URL(
						url2));
				page2 = webClient.getPage(request);
				String host = page2.getUrl().getHost();
				if(StringUtils.equals("opm.be.mi.com", host)){
					success_flag = true;
					System.out.println("cookie登陆");
				}else{
					System.out.println("Cookies:"+webClient.getCookieManager().getCookies().toString());
					System.out.println("cookies已失效");
				}
			}
			if(!success_flag){
				String url = "https://cas.mioffice.cn/login?service=http%3A%2F%2Fopm.be.mi.com%2Fsqlquery%2Findex";
				String url2 = "https://cas.mioffice.cn/login";
				WebRequest request = new WebRequest(new URL(
						url));
				HtmlPage page = webClient.getPage(request);
				HtmlInput  userName = page.getElementByName("username");
				HtmlInput  pwd = page.getElementByName("password");
				userName.setValueAttribute("wenjie");
				pwd.setValueAttribute("1026wjpyzhxWJ");
				HtmlElement   button = (HtmlElement) page.getElementById("message_LOGIN_IMMEDIATELY");
		        page2 = button.click();
			}
	         HtmlElement databseListDom = (HtmlElement) page2.getElementById("database-list");
	         Iterable<DomElement> ss = databseListDom.getChildElements();//获取数据库列表
	        String sql = "select * from `tb_asset_apply_record`";
	         CountParsr countParsr = new CountParsr();
	         TableParser tableParser = new TableParser();
	         int countNum = countParsr.getSqlCount(page2, sql);
	         System.out.println(countNum);
	         List s = tableParser.getTableList(tableParser.findTabel(page2));
	         //获取cookie
	         if(!cookie_enable){
	        	 System.out.println("重新保存cookie");
	        	 Set<Cookie> cookies = webClient.getCookieManager().getCookies();
		         FileWriter  fw = new FileWriter("cookie");
		         BufferedWriter writer = new BufferedWriter(fw);
		         for(Cookie cookie : cookies) {
		        	 writer.write( JSONObject.fromObject(cookie).toString());
		        	 writer.newLine();
		         }
		         writer.flush();
		         writer.close();
		         fw.close();
	         }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
